package com.cxx.autoconfigure.web;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.cxx.autoconfigure.config.CustomProperties;
import com.cxx.autoconfigure.interceptor.AuditInterceptor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 自动配置 实现WebMvcConfigurer
 * <p>
 * SpringBoot MVC总体执行顺序：
 * 1. 进入Tomcat容器
 * 2. 进入Filter过滤器
 * 3. 进入Servlet容器
 * 4. 进入Interceptor拦截器
 * 5. 进入Controller控制器
 * 6. 进入AOP
 */
@Configuration()
@Import({DefaultExceptionAdvice.class, AuditBodyAdvice.class, CustomProperties.class})
public class ServerAutoConfiguration implements WebMvcConfigurer {
    @Resource
    private CustomProperties customProperties;

    /**
     * 注册拦截器  需要实现 WebMvcConfigurer 接口
     * @param registry 注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册安全拦截器
        // registry.addInterceptor(new SecurityInterceptor());
        // 注册审计拦截器
        registry.addInterceptor(new AuditInterceptor(customProperties.getBasePackage()));
        // 注册Sa-Token拦截器 登录校验
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .excludePathPatterns("/error", "/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**")
                .excludePathPatterns("/files/**")
                .excludePathPatterns("/doc.html", "/webjars/**");
    }

    /**
     * 配置CORS跨越 需要实现 WebMvcConfigurer 接口
     * @return 过滤器
     */
    @Bean
    @Order(-128)
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有来源
        config.addAllowedOrigin("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有请求方法
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
